#!/usr/bin/env python

import threading
import time
import gobject
import gtk
import guiLogic

class my_window():
    def delete_event(self, widget, event, data=None):
        # If you return FALSE in the "delete_event" signal handler,
        # GTK will emit the "destroy" signal. Returning TRUE means
        # you don't want the window to be destroyed.
        # This is useful for popping up 'are you sure you want to quit?'
        # type dialogs.
        print "delete event occurred"

        # Change FALSE to TRUE and the main window will not be destroyed
        # with a "delete_event".
        return False

    def destroy(self, widget, data=None):
	if self.createq == True:	
		self.c.stop('None','None')
		self.t.stop('None','None')
        print "destroy signal occurred"
        gtk.main_quit()

    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
	self.window.set_position(gtk.WIN_POS_CENTER)
	self.window.set_title("SMS FEEDBACK")
	self.window.set_default_size(600, 300)
        # When the window is given the "delete_event" signal (this is given
        # by the window manager, usually by the "close" option, or on the
        # titlebar), we ask it to call the delete_event () function
        # as defined above. The data passed to the callback
        # function is NULL and is ignored in the callback function.
        self.window.connect("delete_event", self.delete_event)
    
        # Here we connect the "destroy" event to a signal handler.  
        # This event occurs when we call gtk_widget_destroy() on the window,
        # or if we return FALSE in the "delete_event" callback.
        self.window.connect("destroy", self.destroy)
    
        # Sets the border width of the window.
        self.window.set_border_width(10)
	self.vb = gtk.VBox()
	self.hb = gtk.HBox()
	label = gtk.Label("What do you want to do?")
	button_create = gtk.Button("Create a quizz")
	button_create.connect("clicked", self.createQuiz)
	button_grade = gtk.Button("Grade a quizz")
	button_grade.connect("clicked", self.gradeQuiz)

	self.vb.pack_start(label)
	self.hb.pack_start(button_grade)
	self.hb.pack_start(button_create)
	self.vb.pack_start(self.hb)
	
	self.window.add(self.vb)
	self.window.show_all()

	self.createq = False
	self.gradeq = False

    def createQuiz(self, data1):
	self.createq=True
	gtk.Widget.destroy(self.vb)
        # create a new window
        #self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
	#self.window.set_title("SMS FEEDBACK")
	#self.window.set_default_size(600, 300)
	self.hb = gtk.HBox()
	self.vb = gtk.VBox()
	self.la=gtk.Label()
	self.lb=gtk.Label()
	self.lb.set_line_wrap(True)
	self.lc=gtk.Label()
	self.lc.set_line_wrap(True)
	self.t=MyThread(self.la,self.lb,self.lc,self)
	self.l2=gtk.Label("Connecting...")
	self.c = MyConnec(self.l2,self)
	self.logic = guiLogic.guiLogic()
    
        self.wusername = gtk.Entry()
	self.wusername.set_text("username")
        self.wpassword = gtk.Entry()
	self.wpassword.set_text("password")
	self.wpassword.set_visibility(False)
	
	hb2=gtk.HBox()
	#The dropdown menu a ComboBox
	self.wconfig_file=gtk.FileChooserButton("Choose config file")
	#self.wconfig_file=gtk.combo_box_new_text()
	#Filling the dropdown menu with the list from config_list
	#config_list=self.logic.getFiles()[0]
	#for i in range(len(config_list)):
		#self.wconfig_file.append_text(config_list[i])
	text2 = gtk.Label("Your Configuration file:")
	hb2.pack_start(text2)
	hb2.pack_start(self.wconfig_file)


	hb3=gtk.HBox()
	self.wdrt=gtk.FileChooserButton("Choose directory")
	self.wdrt.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
	text3 = gtk.Label("Where to save the answers:")
	hb3.pack_start(text3)
	hb3.pack_start(self.wdrt)

	hb4=gtk.HBox()
	text4=gtk.Label("Number of questions:")
	#The dropdown menu a ComboBox
	self.wnquestions=gtk.Entry()
	hb4.pack_start(text4)
	hb4.pack_start(self.wnquestions)

	text3 = gtk.Label("Enter you gmail account and password below:")

	self.next=gtk.Button("Next")
	self.next.connect("clicked", self.update1)

	self.vb.pack_start(hb2)
	self.vb.pack_start(hb3)
	self.vb.pack_start(hb4)
	self.vb.pack_start(text3)
	self.vb.pack_start(self.wusername)
	self.vb.pack_start(self.wpassword)
	self.vb.pack_start(self.next)
	
	self.window.add(self.vb)
    
        # and the window
        self.window.show_all()

    def update1(self,data1):
	#To get the selected text from the dropdown menu
	#model = self.wconfig_file.get_model()
      	#active = self.wconfig_file.get_active()
      	#if active > 0:
        config_file=self.wconfig_file.get_filename()
	drt = self.wdrt.get_filename()
	#else:
		#config_file="None"
	print "CONFIG FILE=", config_file, "DIRECTORY=", drt
	self.logic.setWindowOneVariables(config_file,drt,self.wnquestions.get_text()\
		,self.wusername.get_text(),self.wpassword.get_text())

	#self.c.username=self.username
	#self.c.password=self.password
	self.c.start()

	gtk.Widget.destroy(self.vb)
	button_stop=gtk.Button("Cancel")
	button_stop.connect("clicked", self.destroy)
	self.vb.pack_start(self.l2)
	self.vb.pack_start(button_stop)
	self.window.add(self.vb)
	self.window.show_all()
	

    def update2(self,data1):
	gtk.Widget.destroy(self.vb)
	self.vb=self.vb = gtk.VBox()
	hb = gtk.HBox()
	text2=gtk.Label("Connected!")
	self.vb.pack_start(text2)
	self.t.start()

	button_stop = gtk.Button("Stop")
	button_stop.connect("clicked", self.t.stop, None)
	button_next = gtk.Button("Next")
	button_next.connect("clicked", self.update3)
	hb.pack_start(button_stop)
	hb.pack_start(button_next)
	self.vb.pack_start(self.la)
	self.vb.pack_start(self.lb)
	self.vb.pack_start(self.lc)
	self.vb.pack_start(hb)

	self.window.add(self.vb)
   
       	# and the window
       	self.window.show_all()

    def update3(self,data1):
	self.logic.endQuiz()
	self.t.stop(None, None)
	gtk.Widget.destroy(self.vb)
	self.vb= gtk.VBox()
	text1=gtk.Label(self.logic.responseSummary())
	self.vb.pack_start(text1)
	button_done=gtk.Button("Done")
	button_done.connect("clicked", self.destroy)
	self.vb.pack_start(button_done)
	self.window.add(self.vb)
	self.window.show_all()

    def gradeQuiz(self,data1):
	self.gradeq = True
	gtk.Widget.destroy(self.vb)
	self.vb=gtk.VBox()
	hb1 = gtk.HBox()
	text1 = gtk.Label("Quiz:")
	self.wquiz_file = gtk.FileChooserButton("Choose quiz file")
	button_next = gtk.Button("Next")

	hb1.pack_start(text1)
	hb1.pack_start(self.wquiz_file)
	self.vb.pack_start(hb1)
	self.vb.pack_start(button_next)

	self.window.add(self.vb)
	self.window.show_all()
		

    def main(self):
        # All PyGTK applications must have a gtk.main(). Control ends here
        # and waits for an event to occur (like a key press or mouse event).
        gtk.main()

class MyConnec(threading.Thread):
	def __init__(self, label,window):
		super(MyConnec, self).__init__()
		self.label = label
		self.quit = False
		self.w=window

	def update_label(self, counter):
		if self.w.logic.initializeQuizDone:
			self.quit=True
			self.w.update2('None')
		else:
			self.label.set_text("Impossible to connect")
		return False

	def run(self):
		counter = 0
		self.w.logic.initializeQuiz()
		while not self.quit :
			counter += 1
			gobject.idle_add(self.update_label, counter)
			time.sleep(1)

	def stop(self, data1, data2):
		self.initializeQuizDone = True

class MyThread(threading.Thread):
	def __init__(self, label1,label2,label3,window):
		super(MyThread, self).__init__()
		self.label1 = label1
		self.label2 = label2
		self.label3 = label3
		self.w =  window
		self.quit = False

	def update_label(self):
		self.w.logic.collectionLoop()
		self.label1.set_text(self.w.logic.countResponses)
		self.label2.set_text(self.w.logic.recentResponses)
		self.label3.set_text(self.w.logic.totalResponses)
		return False

	def run(self):
		counter = 0
		while not self.quit:
			gobject.idle_add(self.update_label)
			time.sleep(10)

	def stop(self, data1, data2):
		self.quit = True


# If the program is run directly or passed as an argument to the python
# interpreter then create a HelloWorld instance and show it
if __name__ == "__main__":
	gobject.threads_init()
	w = my_window()
	w.main()
